<template>
  <div>
    <div
      style="
        text-align: center;
        background-color: black;
        color: white;
        width: 100%;
        height: 80px;
        line-height: 80px;
      "
    >
      <h2>短信验证码登录</h2>
    </div>
    <van-form @submit="onSubmit">
      <van-cell-group inset>
        <van-field
          v-model="username"
          name="username"
          label="手机号"
          placeholder="手机号"
          :rules="[
            { pattern: pattern1, required: true, message: '请填写正确手机号' },
          ]"
        />
        <van-field
          v-model="password"
          type="password"
          name="password"
          label="密码"
          placeholder="密码"
          :rules="[
            { pattern: pattern2, required: true, message: '请填正确写密码' },
          ]"
        />
        <van-field
          v-model="sms"
          label="验证码"
          placeholder="获取验证码"
          :rules="[{ required: true, message: '请点击获取验证码' }]"
        >
          <template #button>
            <van-button v-if="time == 0">获取验证码</van-button>
            <van-button v-else>{{ time }}s</van-button>
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          登录
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { ref } from "vue";

import { loginApi } from "@/api/api";
import { showToast } from "vant";
import { useRoute, useRouter } from "vue-router";
import { mapState } from "pinia";

const router = useRouter();
const route = useRoute();
const username = ref("");
const password = ref("");

const pattern1 = /^1[3-9]\d{9}$/;
const pattern2 = /^\d{6,12}$/;

const onSubmit = (values) => {
  console.log("submit", values);
  loginApi(username.value, password.value).then((res) => {
    if (res.data.code == 0) {
      showToast("登陆成功");

      localStorage.setItem("token", res.data.data.token);
      localStorage.setItem("username", res.data.data.username);

      router.push("/home/my");
    }
  });
};

const time = 0;
</script>

<style lang="scss" scoped></style>
